import { url_user, url_user_info, url_user_permission } from "@/comm/api";
import { get, patch, post, remove } from "@/comm/request";
import { defineStore } from "pinia";

interface User {
    _id: string;
    username: string;
    password?: string;
    roles: string[];
}

interface IState {
    curUser: User;
    list: User[];
    info: any,
}

export const useUserStore = defineStore({
    id: "user",
    state: (): IState => ({
        curUser: null as any,
        list: [],
        info: null
    }),
    actions: {
        async load() {
            let res: any = await get(url_user);
            console.log("res", res)
            this.list = res.data;
        },
        async getInfo() {
            let res: any = await get(url_user_info);
            console.log("res", res);

            this.info = res?.data;
        },

        async add(data: any) {
            let { _id, ...param } = data;
            console.log("param", param)
            let res: any = await post(url_user, param, true);
            console.log("res", res)
            // this.list = res.data;
        },
        async update(data: any) {
            let { _id, ...param } = data;
            console.log("param", param)
            let res: any = await patch(url_user + "/" + _id, param, true);
            console.log("res", res)
            // this.list = res.data;
        },
        async remove(id: string) {
            let res: any = await remove(url_user + "/" + id);
            console.log("res", res)
            // this.list = res.data;
        },
        async getpermissions(id: string) {
            let res: any = await get(url_user_permission + "/" + id);
            console.log("res", res)
        },
        async login(param: any) {
            let res: any = await post(url_user + "/login", param, true);
            console.log(res);
            if (res.code == 0) {
                localStorage.setItem("token", res.data);
                await this.getInfo();
            }
        },
        async logout() {
            localStorage.removeItem("token");
            this.info = null;
        }

    }
});
